package com.wjh.controller;

import com.wjh.listener.Consumer;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.MessageNotWriteableException;

@RestController
public class JmsController implements ApplicationContextAware {

   private ApplicationContext applicationContext;
    /**
     * 线下
     */
    @Autowired
    private JmsTemplate offlineJmsTemplate;
    /**
     * 线上
     */
//    @Autowired
//    private JmsTemplate onlineJmsTemplate;


//    @GetMapping("onSend")
//    public String onSend() throws MessageNotWriteableException {
//        ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
//        activeMQTextMessage.setText("test");
//        onlineJmsTemplate.convertAndSend(new ActiveMQQueue("jms-Reply"), activeMQTextMessage);
//        return "success";
//    }

    /**
     * 模拟生产者生产消息
     * @param queue
     * @return
     * @throws MessageNotWriteableException
     */
    @GetMapping("offSend/{queue}")
    public String offSend(@PathVariable("queue") String queue) throws MessageNotWriteableException {
        ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
        activeMQTextMessage.setText("test");
        offlineJmsTemplate.convertAndSend(new ActiveMQQueue(queue), activeMQTextMessage);
        applicationContext.getBean("consumer", Consumer.class);
        return "success";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

}
